package com.activiti;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangbowen@heytea.com
 * @since 2020-05-28 18:34
 */
@RestController
@RequestMapping("/v2")
public class MyRest2Controller {

    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;

    @GetMapping(value = "/process")
    public void startProcessInstance(@RequestParam String businessId) {
        Map<String, Object> variables = new HashMap<>();
        // 设置初始值扫描完整个流程（正常流程）
        variables.put("money", 3);
        runtimeService.startProcessInstanceByKey("createProcess", createBusinessKey(businessId), variables);
    }

    @RequestMapping(value = "/tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<TaskRepresentation> getTasks(@RequestParam String businessId) {
        List<Task> assigneeTasks = taskService.createTaskQuery()
            .processInstanceBusinessKey(createBusinessKey(businessId)).taskUnassigned().list();
        // TODO 自己的权限系统，不用listener 在这里过滤也可以
        List<TaskRepresentation> dtos = new ArrayList<>();
        for (Task task : assigneeTasks) {
            dtos.add(new TaskRepresentation(task.getId(), task.getName()));
        }
        return dtos;
        //TODO 可以用getFormKey 来处理，只是提交任务的时候需要传businessId和formKey，因为要获取taskId;
    }

    @RequestMapping(value = "/planProject", method = RequestMethod.GET)
    public void commitPlanProject(@RequestParam String taskId, @RequestParam Integer money) {

        Map<String, Object> variables = new HashMap<>();
        // 全局变量
        variables.put("money", money);
        taskService.complete(taskId, variables);
    }

    private String createBusinessKey(String businessId) {
        return "p." + businessId;
    }
}
